/**
 * 版本状态管理
 */
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { versionAPI } from '@/api/version'
import type { VersionOption } from '@/types/version'

export const useVersionStore = defineStore('version', () => {
  // 状态
  const versions = ref<VersionOption[]>([])
  const loading = ref(false)
  const lastFetchTime = ref<number>(0)
  const searchCache = ref<Map<string, VersionOption[]>>(new Map())
  
  // 计算属性
  const isDataFresh = computed(() => {
    return Date.now() - lastFetchTime.value < 10 * 60 * 1000 // 10分钟内的数据视为新鲜
  })
  
  const versionOptions = computed(() => {
    return versions.value.map(version => ({
      label: version.name || '',
      value: version.name || '',
      disabled: !version.is_active
    }))
  })
  
  // 方法
  async function fetchVersions(projectId?: string, search?: string) {
    // 检查缓存
    const cacheKey = `${projectId || 'all'}_${search || ''}`
    if (search && searchCache.value.has(cacheKey)) {
      return searchCache.value.get(cacheKey)!
    }
    
    loading.value = true
    
    try {
      const response = await versionAPI.getVersions({
        project_id: projectId,
        search,
        page: 1,
        size: 100
      })
      
      const versionList = response?.data?.items?.map((item: { id: any; name: any; description: any; status: any; project_id: any }) => ({
        id: item.id,
        name: item.name,
        description: item.description,
        is_active: item.status !== 'archived',
        project_id: item.project_id,
        project_name: ''
      })) || []
      
      if (search) {
        // 缓存搜索结果
        searchCache.value.set(cacheKey, versionList)
      } else {
        versions.value = versionList
        lastFetchTime.value = Date.now()
      }
      
      console.debug('版本数据获取成功:', {
        projectId,
        search,
        count: versionList.length
      })
      
      return versionList
    } catch (error) {
      console.error('获取版本数据失败:', error)
      ElMessage.error('获取版本数据失败')
      return []
    } finally {
      loading.value = false
    }
  }
  
  async function searchVersions(query: string, projectId?: string): Promise<VersionOption[]> {
    if (!query.trim()) {
      return versions.value.filter(v => !projectId || v.project_id === projectId)
    }
    
    return await fetchVersions(projectId, query)
  }
  
  function getVersionById(versionId: string): VersionOption | undefined {
    return versions.value.find(version => version.id === versionId)
  }
  
  function getVersionsByProject(projectId: string): VersionOption[] {
    return versions.value.filter(version => version.project_id === projectId)
  }
  
  function clearCache() {
    searchCache.value.clear()
    console.debug('版本搜索缓存已清空')
  }
  
  function refreshVersions() {
    lastFetchTime.value = 0
    clearCache()
    return fetchVersions()
  }
  
  // 清理函数
  function $reset() {
    versions.value = []
    loading.value = false
    lastFetchTime.value = 0
    searchCache.value.clear()
  }
  
  return {
    // 状态
    versions,
    loading,
    lastFetchTime,
    
    // 计算属性
    isDataFresh,
    versionOptions,
    
    // 方法
    fetchVersions,
    searchVersions,
    getVersionById,
    getVersionsByProject,
    clearCache,
    refreshVersions,
    $reset
  }
})